package com.lichuandi.controller;


import org.springframework.web.bind.annotation.*;
import java.util.Base64;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.IOException;

/**
 * @author admin
 */
@RestController
public class ImageCropController {

    @PostMapping("/process_crop")
    public String processCrop(@RequestBody CropRequest request) {
        try {
            // 解码base64图像
            byte[] imageBytes = Base64.getDecoder().decode(request.getImage());
            BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageBytes));

            // 裁剪图像
            BufferedImage croppedImage = originalImage.getSubimage(
                    request.getX(),
                    request.getY(),
                    request.getWidth(),
                    request.getHeight()
            );

            // 将裁剪后的图像转回base64
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(croppedImage, "png", baos);
            String croppedBase64 = Base64.getEncoder().encodeToString(baos.toByteArray());

            return croppedBase64;
        } catch (IOException e) {
            return "图像处理错误: " + e.getMessage();
        }
    }

    // 内部类，用于接收JSON请求
    public static class CropRequest {
        private int x;
        private int y;
        private int width;
        private int height;
        private String image;

        // Getters and Setters
        public int getX() { return x; }
        public void setX(int x) { this.x = x; }

        public int getY() { return y; }
        public void setY(int y) { this.y = y; }

        public int getWidth() { return width; }
        public void setWidth(int width) { this.width = width; }

        public int getHeight() { return height; }
        public void setHeight(int height) { this.height = height; }

        public String getImage() { return image; }
        public void setImage(String image) { this.image = image; }
    }
}
